//
//  LAPolyline.m
//  OutdoorAssistantApplication
//
//  Created by 罗亮富 on 2018/6/26.
//  Copyright © 2018年 Lolaage. All rights reserved.
//

#import "LAPolyline.h"

@implementation LAPolyline
{
    BOOL _coordianteUpdated;
    MKMapRect _myBoudingRect;
    CLLocationCoordinate2D _centerCoord;
@protected
    __weak MKPolylineRenderer *_renderer;
}

-(instancetype)init
{
    self = [super init];
    if(self)
    {
        self.rendererClass = [MKPolylineRenderer class];
#if TARGET_OS_IPHONE
        self.lineColor = [UIColor redColor];
        self.fillColor = [UIColor yellowColor];
#else
        self.lineColor = [NSColor redColor];
        self.fillColor = [NSColor yellowColor];
#endif
        self.lineStrokeWidth = 4.0;
        self.lineJoin = kCGLineJoinRound;
        self.lineCap = kCGLineCapRound;
        self.miterLimit = 10;
    }
    return self;
}

-(void)setNeedsUpdateBoundingAndCenter
{
    double minx = 999999999999;
    double miny = 999999999999;
    double maxx = -999999999999;
    double maxy = -999999999999;
    
    MKMapPoint *pts = self.points;
    NSUInteger ptCnt = self.pointCount;
    for(NSUInteger i=0; i<ptCnt; i++)
    {
        MKMapPoint pt = *(pts + i);
        
        if(pt.x > maxx)
            maxx = pt.x;
        if(pt.y > maxy)
            maxy = pt.y;
        if(pt.x < minx)
            minx = pt.x;
        if(pt.y < miny)
            miny = pt.y;
    }
    
    _myBoudingRect = MKMapRectMake(minx,miny,maxx-minx, maxy-miny);
    _centerCoord = MKCoordinateForMapPoint(MKMapPointMake((maxx-minx)/2,(maxy-miny)/2));
}

-(MKMapRect)boundingMapRect
{
    if(MKMapRectIsEmpty(_myBoudingRect))
        _myBoudingRect = [super boundingMapRect];
    
    return _myBoudingRect;
    
}

-(CLLocationCoordinate2D)coordinate
{
    if(fabs(_centerCoord.latitude)<0.00001 && fabs(_centerCoord.longitude)<0.00001)
        _centerCoord = [super coordinate];
    
    return _centerCoord;
}


-(void)refreshPolyLine
{
    if(_renderer)
    {
        [self setupRenderer:_renderer];
        [_renderer setNeedsDisplay];
    }
}


-(void)setupRenderer:(MKOverlayRenderer *)renderer
{
    if([renderer isKindOfClass:[MKPolylineRenderer class]])
    {
        MKPolylineRenderer *r = (MKPolylineRenderer *)renderer;
        r.lineWidth = self.lineStrokeWidth;
        r.strokeColor = self.lineColor;
        r.lineJoin = self.lineJoin;
        r.lineCap = self.lineCap;
        r.miterLimit = self.miterLimit;
        r.lineDashPattern = self.lineDashPattern;
    }
}


-(MKPolylineRenderer *)renderer
{
    MKPolylineRenderer *rd = _renderer;
    if(!rd)
    {
        rd = [[self.rendererClass alloc] initWithPolyline:self];
        _renderer = rd;
        [self setupRenderer:_renderer];
    }
    
    return rd;
}

@end
